package sing.rabbit.provider.send;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @author xing
 * @date 2022/9/7 19:54
 */
@Component
public class SimpleMessageSender {
    @Autowired
    public RabbitTemplate template;
    @Autowired
    public Queue simpleQueue;

    /**
     * 定时循环调用发送消息 <br>
     * 仅发送 String 类型消息
     *
     */
    // @Profile("string") // @Profile 没有用, 如果只发 String 消息，把下边的 send 注释掉（或者分离到两个类）
    @Scheduled(fixedDelay = 1000, initialDelay = 500)
    public void send() {
        String message = "Hello World!";
        this.template.convertAndSend(simpleQueue.getName(), message);
        System.out.println(" [x] Sent '" + message + "'");
    }

    /**
     * 定时循环发送 Message 类型的带 Headers 的消息，
     */
    // @Profile("message") // @Profile 没有用, 如果只发 Message 消息，把上边的 send 注释掉
    @Scheduled(fixedDelay = 1000, initialDelay = 500)
    public void send2() {
        String message = "Hello World!";
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setHeader("token", "This is a token");
        messageProperties.setHeader("rabbit", "Hello Rabbit");
        Message messageClass = new Message(message.getBytes(), messageProperties);
        this.template.convertAndSend(simpleQueue.getName(), messageClass);
        System.out.println(" [x] Sent '" + message + "'");
    }
}
